package com.wct.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.wct.spzx.model.entity.system.SysUser;
import com.wct.spzx.model.vo.common.Result;
import com.wct.spzx.model.vo.common.ResultCodeEnum;
import com.wct.spzx.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author chang
 * @date 2023/12/11/011 19:56
 */

@Slf4j
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求方式
        //如果请求方式是options(预检请求)，则直接返回
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //2.从请求头中获取token
        String token = request.getHeader("token");
        //3.如果token为空，则返回错误提示
        if (StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return false;
        }
//        log.info("url:{} token: {}", request.getRequestURI(), token);
        //4.如果token不为空，则从redis中获取用户信息
        String userInfoString = redisTemplate.opsForValue().get("user:login:" + token);
        //5.如果redis查询不到信息，则返回错误信息
        if (StrUtil.isEmpty(userInfoString)) {
            responseNoLoginInfo(response);
            return false;
        }
        //6.如果redis查询到信息，把用户信息放到ThreadLocal中
        SysUser sysUser = JSON.parseObject(userInfoString, SysUser.class);
        AuthContextUtil.set(sysUser);
        //7.更新redis用户信息数据过期时间
        redisTemplate.expire("user:login:" + token, 5, TimeUnit.MINUTES);
        //8.放行
        return true;
    }

    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // ThreadLocal删除
        AuthContextUtil.remove();
    }
}
